<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写一个Promise</title>
</head>
<body>
    <script type="text/javascript">
        const PENDING = 'PENDING'
        const FULFILLED = 'FULFILLED'
        const REJECTED = 'REJECTED'
        class MyPromise {
            constructor(executor){
                // 初始化状态
                this.status = PENDING

                // 定义一个成功状态的返回值
                this.value = undefined

                // 定义一个失败状态的返回值
                this.reason = undefined

                // 成功的回调
                let resolve = value => {
                    if (this.status === PENDING) {
                        this.status = FULFILLED
                        this.value = value
                    }
                }

                // 失败的回调
                let reject = reason => {
                    if (this.status === PENDING) {
                        this.status = REJECTED
                        this.reason = reason
                    }
                }

                try {
                    executor(resolve, reject)
                } catch (error) {
                    reject(error)
                }
            }
            
            then(onFulfilled, onRejected) {
                if (this.status === FULFILLED) {
                    isFunction(onFulfilled) ? onFulfilled(this.value) : (value) => {return value}
                }
                if (this.status === REJECTED) {
                    isFunction(onRejected)?onRejected(this.reason) : (reason) => {throw reason}
                }
            }
            isFunction(value) {
                return typeof value === 'function'
            }
        }
        const promise = new MyPromise((resolve, reject) => {
            resolve('成功')
        }).then(data => {
            console.log(data)
        })
        
    </script>
</body>
</html>